package com.well.register.eventAndlistener;

import com.well.register.cluster.ClusterConfig;
import com.well.register.console.service.ServerService;
import com.well.register.netty.ConnClusterClient;
import com.well.register.netty.RegisterServer;
import com.well.register.util.ThreadUtils;
import com.well.rpc.model.ClusterServerModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class ContextRefreshedLister implements ApplicationListener<ContextRefreshedEvent> {
    @Resource
    private RegisterServer registerServer;
    @Resource
    ClusterConfig clusterConfig;
    @Resource
    ServerService serverService;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent applicationEvent) {

        if (clusterConfig.isEnable()) {
            List<ClusterServerModel> clusterServer = clusterConfig.getClusterServer();
            ScheduledExecutorService scheduledExecutorService = ThreadUtils.scheduledThreadPool();

            for (int i = 0; i < clusterServer.size(); i++) {
                ClusterServerModel clusterServerModel = clusterServer.get(i);
                scheduledExecutorService.schedule(() -> {
                    ConnClusterClient.run(clusterServerModel.getHost(), clusterServerModel.getPort());
                }, 0, TimeUnit.SECONDS);
            }
        }
        //恢复服务注册状态
        serverService.restoreRegisterServerState();
        registerServer.run();
    }
}
